package tcp

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"hcy-api/lib/cmdutil"
	"hcy-api/lib/utils"
	"hcy-api/structs/base"
	"hcy-api/structs/enum"
	"hcy-api/structs/vap"
	"time"
	"vap_host/global"
)

func (c *Client) sayHi() {
	// 通知服务端主机在线
	err := c.WriteMessage(base.ClientResponse{
		MsgTime:    time.Now().Unix(),
		Result:     c.ClientId,
		ResultType: enum.Online,
	})
	if err != nil {
		logrus.Errorf("sayHi error: %v", err)
		return
	}

	// 调用举手插件
	resp, err := c.execPlugin(enum.BasePlugin, []string{"-info"}, enum.SayHi)
	if err != nil {
		logrus.Errorf("sayHi error: %v", err)
		return
	}
	var appHost vap.AppHost
	err = json.Unmarshal([]byte(resp.Result), &appHost)
	if err != nil {
		logrus.Errorf("sayHi error: %v。context :[%s]", err, resp.Result)
		return
	}
	// 如果服务配置了rdp ip和端口 就使用配置的信息填充
	if global.Conf.AppHost.RdpIp != "" {
		appHost.Ip = global.Conf.AppHost.RdpIp

	}
	if global.Conf.AppHost.RdpPort != 0 {
		appHost.RdpPort = global.Conf.AppHost.RdpPort
	}
	appHost.Uid = global.Conf.AppHost.UID
	resp.Result = utils.Obj2Str(appHost)
	_ = c.WriteMessage(resp)
	return
}

// createWinAccount 创建windows rdp 账户,body 参数为账户，密码已经写在cli中的
func (c *Client) createWinRdpAccount(in base.ClientInstruct) {
	var pi vap.PluginInstruct
	err := json.Unmarshal([]byte(in.Body), &pi)
	if err != nil {
		return
	}
	logrus.Debugf("createWinRdpAccount instruct:%+v", in)
	resp, err := c.execPlugin(enum.BasePlugin, pi.Args, enum.CreateRdpWinAccount)
	if err != nil {
		logrus.Errorf("createWinRdpAccount error: %v", err)
		return
	}
	logrus.Debugf("createWinRdpAccount instruct result:%+v", in)
	_ = c.WriteMessage(resp)
	return
}

// uploadApps 上传云应用信息
func (c *Client) uploadApps(in base.ClientInstruct) {
	var pi vap.PluginInstruct
	err := json.Unmarshal([]byte(in.Body), &pi)
	if err != nil {
		return
	}
	resp, err := c.execPlugin(enum.BasePlugin, pi.Args, enum.CloudApps)
	if err != nil {
		logrus.Errorf("uploadApps error: %v", err)
		return
	}
	_ = c.WriteMessage(resp)
	return
}

// execPlugin 执行插件
func (c *Client) execPlugin(cmd string, args []string, rType string) (res base.ClientResponse, err error) {
	plug := base.PluginInstruct{
		Cmd:  cmd,
		Args: args,
	}
	var stdout string
	t1 := time.Now().Unix()
	stdout, err = cmdutil.Run(plug)
	if err != nil {
		return
	}
	t2 := time.Now().Unix()
	res = base.ClientResponse{
		ElapsedTime: t2 - t1,
		Result:      stdout,
		ResultType:  rType,
		Instruct:    utils.Obj2Str(plug),
		MsgTime:     time.Now().Unix(),
	}
	return
}
